import { Component, OnInit } from '@angular/core';
import { ActivatedRoute, Router } from '@angular/router';
import { Location } from '@angular/common';

import { BookService } from '../../../services/book.service';
import { TransactionService } from '../../../services/transaction.service';
import { aroAnimation } from '../../../animation';

@Component({
	selector: 'app-bookdetail',
	templateUrl: './bookdetail.component.html',
	styleUrls: ['./bookdetail.component.css'],
	animations: [aroAnimation]
})
export class BookdetailComponent implements OnInit {

	public bookId: string = '';
	public readerId: string = localStorage.getItem('ReaderId');

	public tempbook: any = {};
	public book: any = {};

	public msg: string = '';
	public timer: any;
	public state: boolean = false;

	public BookcaseSummary: number = JSON.parse(localStorage.getItem('BookcaseSummary'));

	constructor(private location: Location, private currentRouter: ActivatedRoute, private router: Router,
		private bookService: BookService, private transactionService: TransactionService
	) { }

	ngOnInit() {
		this.bookId = this.currentRouter.snapshot.params['id'];

		this.bookService.getSingle(this.bookId).subscribe(res => {
			// console.log(res);
			if (res.Code == 100) {
				this.tempbook = res.Data;
				this.book = {
					Image: (this.tempbook as any).Book.Image,
					Name: (this.tempbook as any).Book.Name,
					Author: (this.tempbook as any).Book.Author.Name,
					Publisher: (this.tempbook as any).Book.Publisher.Name,
					PublishDate: (this.tempbook as any).Book.PublishDate,
					Number: (this.tempbook as any).Number,
					Introduce: (this.tempbook as any).Book.Introduce
				};
			}
		});
	}

	public addToBookcase_onclick(): void {

		if (!this.readerId) {
			// this.router.navigate(['./bookcase']);
			this.msg = '请先登录';
			this.state = true;
			this.timer = setInterval(() => {
				this.state = false;
			}, 1000);
		} else {
			// this.router.navigate(['./bookcase']);
			this.transactionService.addBookShelf(this.bookId, this.readerId).subscribe(res => {
				// console.log(res);
				if (res.Code == 217) {
					this.msg = '该图书已在您的借书架中';
					this.state = true;
					this.timer = setInterval(() => {
						this.state = false;
					}, 1000);
				} else if (res.Code == 214) {
					this.msg = '图书没有库存';
					this.state = true;
					this.timer = setInterval(() => {
						this.state = false;
					}, 1000);
				} else {
					this.msg = '加入借书架成功';
					this.state = true;
					this.timer = setInterval(() => {
						this.state = false;
					}, 1000);
				}
			});
		}

	}

	public goBookcase_onclick(): void {
		this.router.navigate(['./bookcase']);
	}

	public goBack_onclick(): void {
		this.location.back();
	}

}
